<?php

namespace App\Model\Common;

use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Cookie;

class User extends Common
{
    public $registerFields = ['name', 'password', 'email'];

    public function setPasswordAttribute($value)
    {
        if ($value) {
            $this->salt = rand(1000, 9999);

            $this->attributes['password'] = md5($value.$this->salt);
        }
    }

    public function checkPassword($password)
    {
        if ($this->password == md5($password.$this->salt)) {
            return true;
        } else {
            return false;
        }
    }

    public function checkEmailExist($email)
    {
        $email = $email ?: request()->input('email', '');
        if ($email && is_email($email)) {
            $ct = $this->where(array('email' => $email))->count();

            return $ct > 0 ? true : false;
        } else {
            return false;
        }
    }

    public function add($data)
    {
        $data = $data ?: request()->post();
        $this->name = $data['name'];
        $this->password = $data['password'];
        $this->email = $data['email'];
        // var_dump($this->attributes);
        // $this->setPasswordAttribute($data['password']);
        $re = $this->save();

        return $re ? $this : false;
    }

    public function doLogout()
    {
        Session::forget('user:uid');
        Session::forget('user:gid');

        return true;
    }

    public static function logoutTheUser()
    {
        Session::forget('user:uid');
        Session::forget('user:name');
        Session::forget('user:gid');
        Session::forget('user:slog');
    }

    public function logTheUser($user = null, $long = false)
    {
        $uid = $user ? $user->id : $this->id;
        $gid = $user ? $user->group_id : $this->group_id;
        $name = $user ? $user->name : $this->name;
        if (!$uid) {
            $this->error = lang('10005');

            return false;
        }
        $this->doLogout();
        //记录session
        // session('user:uid', $uid);
        Session::put('user:uid', $uid);
        Session::put('user:name', $name);
        // session('user:gid', $gid);
        Session::put('user:gid', $gid);
        //记录强登陆时间
        // session('slog', time());
        Session::put('user:slog', time());
        $sid = Session::getId();
        $skey = make_rank_code(1, 10);
        if ($long) {
            $expire = 604800;   //7天
            cookie('skey', $skey, $expire);
        } else {
            cookie('skey', $skey);
        }
        Cookie::make('_sid_', $sid);

        //写登陆日志
        $LoginLog = new LoginLog();
        // var_dump($uid);
        // exit;
        $LoginLog->uid = $uid;
        $LoginLog->ip = request()->ip();
        $LoginLog->save();

        return true;
    }
}
